<template>
    <!-- 账号密码登录组件 -->
    <div class="form-account">
        <el-form
            ref="ruleFormRef"
            label-width="auto"
            :model="formLabelAlign"
            style="max-width: 600px"
            :rules="rules"
            status-icon
        >
            <el-form-item label="账号" label-position="left" prop="account" class="labelinput">
                <el-input v-model="formLabelAlign.account" />
            </el-form-item>
            <el-form-item label="密码" label-position="left" prop="password" class="labelinput">
                <el-input 
                    placeholder="请输入密码"
                    show-password 
                    v-model="formLabelAlign.password"
                    type="password"/>
            </el-form-item>
        </el-form>
    </div>
</template>
<script setup lang="ts">
import { ref ,reactive} from 'vue';
import type { FormRules ,ElForm } from 'element-plus'

import { useLoginStore } from "@/stores/login/login"
// import { ElMessage } from 'element-plus'
import type {  RuleForm } from "@/types/index"  // 引入类型
import { localCache } from '@/utils/cache';
// 定义表单数据
const formLabelAlign = reactive<RuleForm>({
    account: localCache.getCache("account") ?? '',
    password: localCache.getCache("password") ?? '',
})
// 定义表单校验规则
const rules = reactive<FormRules<RuleForm>>({
    account: [
    { required: true, message: '账号不能为空', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]{3,11}$/, message: '必须是3到11位数字或字母组成~', trigger: 'blur' },
  ],
    password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 6, max: 12, message: '必须是6到12位数字或字母组成~', trigger: 'blur'},
  ],

})
  // 获取表单实例
const ruleFormRef = ref<InstanceType<typeof ElForm>>()

  // 表单校验
  // checked 是父组件传过来的，用来判断是否记住密码
function submitForm (checked: boolean){
  ruleFormRef.value?.validate((valid) => {
    if (valid) {
      // 表单校验通过
      const { account, password } = formLabelAlign
      console.log({account, password});
      // 调用登录接口
        useLoginStore().loginAccountAction({ account, password }).then(res =>{
        // 判断是否取消记住密码
        if(checked){
          // 记住密码
          localCache.setCache("account",account)
          localCache.setCache("password",password)
        }else{
          // 删除账号密码缓存
          localCache.removeCache("account")
          localCache.removeCache("password")
        }
      })
    } else {
      // 表单校验不通过
      ElMessage.error('输入内容不规范，请重新输入~')
    }
  })
}
  

defineExpose({
    submitForm
})
</script>
<style lang="less" scoped>
.form-account{
    :deep(.labelinput .el-form-item__label){
        color: #fff;
    }
}
</style>